<template>
  <div style="padding: 20px; background-color: #f5f5f5; min-height: 85vh;">
    <!-- 顶部：产品基础信息 -->
    <div
      style="display:flex; align-items:flex-start; gap:16px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
      <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;" :src="basicInfo.shopPic"
        :preview-src-list="[basicInfo.shopPic]" fit="cover" />
      <div style="flex:1; min-width: 0;">
        <div style="display:flex; justify-content: space-between; align-items:center;">
          <div>
            <div style="font-size:18px; font-weight:600; color:#303133;">{{ basicInfo.shopName }}</div>
            <div style="margin-top:6px; color:#909399; font-size:13px;">商品信息</div>
          </div>
          <div style="display:flex; gap:8px;">
            <el-button @click="$router.back()">返回</el-button>
          </div>
        </div>
        <div style="display:grid; grid-template-columns: repeat(2, minmax(160px, 1fr)); gap: 12px; margin-top:12px;">
          <table style="width: 100%;border-collapse: collapse;">
            <tbody>
              <tr>
                <td>生产批次： {{ basicInfo.production }}</td>
                <td>保质期： {{ basicInfo.expiration }}</td>
              </tr>
              <tr>
                <td> 生产许可证号： {{ basicInfo.expNumber }}</td>
                <td> 生产企业： {{ basicInfo.enterprise }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 产品检验报告 -->
    <div
      style="margin-top: 12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
      <div style="font-weight:600; margin-bottom:12px;">产品检验报告</div>
      <div style="display:flex; gap:12px; flex-wrap: wrap;">
        <el-image v-for="(pic, index) in basicInfo.pics" :key="index"
          style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden; margin-bottom: 10px;" :src="pic"
          :preview-src-list="basicInfo.pics" fit="cover" />
      </div>
      <el-upload class="upload-demo" :http-request="uploadProductPic" :on-success="handleProductPicSuccess"
        :before-upload="beforeUpload" :limit="10" :file-list="productPicFileList" list-type="picture" name="file"
        multiple>
        <el-icon class="upload-icon">
          <Plus />
        </el-icon>
        <template #tip>
        </template>
      </el-upload>
    </div>

    <!--养殖信息、屠宰信息、深加工信息 -->
    <div style="margin-top:12px;">
      <el-tabs model-value="breeding">
        <!-- 养殖信息标签页 -->
        <el-tab-pane label="养殖信息" name="breeding">
          <div style="padding: 0 0;">
            <el-button plain @click="Handlerupdatefeed">
              修改基础信息
            </el-button>
            <el-button plain @click="Handleraddfeed">
              添加基础信息
            </el-button>
            <!-- 修改弹窗 -->
            <el-dialog v-model="Handupdatefeed" title="修改养殖基础信息" width="600">
              <el-form :model="breedingInfoupdate">
                <el-form-item label="品种" :label-width="formLabelWidth">
                  <el-input v-model="breedingInfoupdate.feedVariety" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="breedingInfoupdate">
                <el-form-item label="来源" :label-width="formLabelWidth">
                  <el-input v-model="breedingInfoupdate.feedSource" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="breedingInfoupdate">
                <el-form-item label="饲养天数" :label-width="formLabelWidth">
                  <el-input v-model="breedingInfoupdate.feedDays" autocomplete="off" />
                </el-form-item>
              </el-form>

              <el-form :model="breedingInfoupdate">
                <el-form-item label="饲料负责人" :label-width="formLabelWidth">
                  <el-input v-model="breedingInfoupdate.feedName" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="breedingInfoupdate">
                <el-form-item label="饲料品牌" :label-width="formLabelWidth">
                  <el-input v-model="breedingInfoupdate.feedFoodName" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="breedingInfoupdate">
                <el-form-item label="出栏日期" :label-width="formLabelWidth">
                  <el-date-picker v-model="breedingInfoupdate.leaveDate" type="date" placeholder="选择日期"
                    format="YYYY年MM月DD日" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-form>

              <!-- 动检证图片上传 -->
              <el-form :model="breedingInfoupdate">
                <el-form-item label="动检证图片" :label-width="formLabelWidth">
                  <el-image
                    style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden; margin-bottom: 10px;"
                    :src="breedingInfoupdate.pic" :preview-src-list="[breedingInfoupdate.pic]" fit="cover"
                    v-if="breedingInfoupdate.pic" />
                  <el-upload class="upload-demo" :http-request="uploadBreedingPic"
                    :on-success="handleBreedingPicSuccess" :before-upload="beforeUpload" :limit="1"
                    :file-list="breedingPicFileList" list-type="picture" name="file">
                    <el-icon class="upload-icon">
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>
              </el-form>

              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="Handupdatefeed = false">取消</el-button>
                  <el-button type="primary" @click="updatefeed">
                    修改
                  </el-button>
                </div>
              </template>
            </el-dialog>

            <!-- 添加弹窗 -->
            <el-dialog v-model="Handaddfeed" title="添加养殖基础信息" width="500">
              <el-form :model="breedingInfoadd">
                <el-form-item label="品种" :label-width="formLabelWidth">
                  <el-input v-model="breedingInfoadd.feedVariety" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="breedingInfoadd">
                <el-form-item label="来源" :label-width="formLabelWidth">
                  <el-input v-model="breedingInfoadd.feedSource" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="breedingInfoadd">
                <el-form-item label="饲养天数" :label-width="formLabelWidth">
                  <el-input v-model="breedingInfoadd.feedDays" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="breedingInfoadd">
                <el-form-item label="饲料负责人" :label-width="formLabelWidth">
                  <el-input v-model="breedingInfoadd.feedName" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="breedingInfoadd">
                <el-form-item label="饲料品牌" :label-width="formLabelWidth">
                  <el-input v-model="breedingInfoadd.feedFoodName" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="breedingInfoadd">
                <el-form-item label="出栏日期" :label-width="formLabelWidth">
                  <el-date-picker v-model="breedingInfoadd.leaveDate" type="date" placeholder="选择日期"
                    format="YYYY年MM月DD日" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-form>
              <el-form-item label="企业" :label-width="formLabelWidth">
                <el-select v-model="breedingInfoadd.companiesId">
                  <el-option v-for="c in compianData" :label="c.companiesName" :value="c.id" />
                </el-select>
              </el-form-item>
              <!-- 动检证图片上传 -->
              <el-form-item label="动检证图片" :label-width="formLabelWidth">
                <el-upload class="upload-demo" :http-request="uploadBreedingPicAdd"
                  :on-success="handleBreedingPicAddSuccess" :before-upload="beforeUpload" :limit="1"
                  :file-list="breedingPicAddFileList" list-type="picture" name="file">
                  <el-icon class="upload-icon">
                    <Plus />
                  </el-icon>

                </el-upload>
              </el-form-item>

              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="Handaddfeed = false">取消</el-button>
                  <el-button type="primary" @click="addfeed">
                    添加
                  </el-button>
                </div>
              </template>
            </el-dialog>

            <!-- 养殖信息块 -->
            <div style="padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">养殖信息</div>
              </div>
              <table>
                <tbody>
                  <tr>
                    <td>品种： {{ breedingInfo[0]?.feedVariety || '' }}</td>
                    <td>来源： {{ breedingInfo[0]?.feedSource || '' }}</td>
                  </tr>
                  <tr>
                    <td> 饲养天数: {{ breedingInfo[0]?.feedDays || '' }}</td>
                    <td> 饲养品牌: {{ breedingInfo[0]?.feedFoodName || '' }}</td>
                  </tr>
                  <tr>
                    <td>饲养负责人: {{ breedingInfo[0]?.feedName || '' }}</td>
                    <td>出栏日期: {{ breedingInfo[0]?.leaveDate ? moment(breedingInfo[0].leaveDate).format("YYYY年MM月DD日") :
                      '' }}</td>
                  </tr>
                </tbody>

              </table>
            </div>
            <!-- 保健信息 -->
            <div
              style="margin-top:12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">保健信息</div>
                <el-button plain @click="addHealthInfoAtIndex(2)">
                  新增一行
                </el-button>
              </div>
              <div>
                <el-table :data="health" style="width: 100%">
                  <el-table-column fixed prop="feedDays" label="饲养天数" width="150">
                    <template #default="scope">
                      <el-input v-if="scope.row.isEditing || scope.row.isNew" v-model="scope.row.feedDays"
                        placeholder="请输入饲养天数" maxlength="5" @input="validateNumber(scope.row.feedDays, 'feedDays')" />
                      <span v-else>{{ scope.row.feedDays }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column fixed prop="healthType" label="保健方式" width="150">
                    <template #default="scope">
                      <el-input v-if="scope.row.isEditing || scope.row.isNew" v-model="scope.row.healthType"
                        placeholder="请输入保健方式" maxlength="30"
                        @input="validateText(scope.row.healthType, 'healthType')" />
                      <span v-else>{{ scope.row.healthType }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column fixed prop="healthWay" label="保健方法" width="150">
                    <template #default="scope">
                      <el-input v-if="scope.row.isEditing || scope.row.isNew" v-model="scope.row.healthWay"
                        placeholder="请输入保健方法" maxlength="30" @input="validateText(scope.row.healthWay, 'healthWay')" />
                      <span v-else>{{ scope.row.healthWay }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="scope">
                      <template v-if="scope.row.isEditing">
                        <el-button link type="primary" size="small" @click="saveHealthInfo(scope.row)">
                          保存
                        </el-button>
                        <el-button link type="primary" size="small" @click="cancelEdit(scope.row)">
                          取消
                        </el-button>
                      </template>
                      <template v-else-if="scope.row.isNew">
                        <el-button link type="primary" size="small" @click="saveHealthInfo(scope.row)">
                          保存
                        </el-button>
                        <el-button link type="primary" size="small" @click="cancelAdd(scope.$index)">
                          取消
                        </el-button>
                      </template>
                      <template v-else>
                        <el-button link type="primary" size="small" @click="editHealthInfo(scope.row)">
                          修改
                        </el-button>
                        <el-button link type="primary" size="small" @click="deleteHealthInfo(scope.$index)">
                          删除
                        </el-button>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <!-- 动检证图片 -->
            <div
              style="margin-top:12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">动检证图片</div>
                <el-button plain @click="addInspectionPic" :disabled="inspectionPics.length >= 9">
                  新增
                </el-button>
              </div>
              <div style="display:flex; gap:12px; flex-wrap:wrap;">
                <div v-for="(pic, index) in inspectionPics" :key="index" style="position: relative;">
                  <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;" :src="pic"
                    :preview-src-list="inspectionPics" fit="cover" />
                  <el-button type="danger" size="small" circle
                    style="position: absolute; top: -8px; right: -8px; width: 20px; height: 20px; font-size: 12px;"
                    @click="deleteInspectionPic(index)">
                    ×
                  </el-button>
                </div>
              </div>
            </div>
            <!-- 企业信息  -->
            <div
              style="margin-top:12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <el-button plain @click="Handlerupdate">
                设置
              </el-button>
              <el-dialog v-model="Handlerupdatecompanies" title="企业信息" width="500">
                <el-form :model="UpdateCompaniesdatafeed">
                  <el-form-item label="企业" :label-width="formLabelWidth">
                    <el-select v-model="UpdateCompaniesdatafeed.id" placeholder="请选择企业">
                      <el-option v-for="c in compianData" :key="c.id" :label="c.companiesName" :value="c.id" />
                    </el-select>
                  </el-form-item>
                </el-form>
                <el-form :model="UpdateCompaniesdatafeed">
                  <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload action="#" :auto-upload="false" :show-file-list="false" :on-change="handleImageChange">
                      <el-image v-if="UpdateCompaniesdatafeed.pic"
                        style="width: 120px; height: 120px; border-radius: 6px; margin-right: 10px;"
                        :src="UpdateCompaniesdatafeed.pic" fit="cover" />
                      <el-button v-else type="primary">点击上传</el-button>
                    </el-upload>
                  </el-form-item>
                </el-form>
                <el-form :model="UpdateCompaniesdatafeed">
                  <el-form-item label="负责人" prop="name">
                    <el-input v-model="UpdateCompaniesdatafeed.chargeName" />
                  </el-form-item>
                </el-form>
                <el-form :model="UpdateCompaniesdatafeed">
                  <el-form-item label="存栏数量" prop="name">
                    <el-input v-model="UpdateCompaniesdatafeed.animalNumber" />
                  </el-form-item>
                </el-form>
                <template #footer>
                  <div class="dialog-footer">
                    <el-button @click="Handlerupdatecompanies = false">取消</el-button>
                    <el-button type="primary" @click="updateCompanies">
                      修改
                    </el-button>
                  </div>
                </template>
              </el-dialog>
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">企业信息</div>
              </div>

              <div style="display:grid; grid-template-columns: repeat(2, minmax(220px, 1fr)); gap: 12px;">
                <table style="width: 100%;border-collapse: collapse;">
                  <tbody>
                    <tr>
                      <td>养殖场： {{ UpdateCompaniesdata.companiesName }}</td>
                      <td>负责人： {{ UpdateCompaniesdata.chargeName }}</td>
                    </tr>
                    <tr>
                      <td> 存栏数量： {{ UpdateCompaniesdata.animalNumber }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <!-- 企业图片  -->
            <div
              style="margin-top:12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">企业图片</div>
              </div>
              <div style="display:flex; gap:12px; flex-wrap:wrap;">
                <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                  :src="breedingInfo[0]?.companiesPic" :preview-src-list="[breedingInfo[0]?.companiesPic]"
                  fit="cover" />
                <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                  :src="breedingInfo[0]?.companiesPic" :preview-src-list="[breedingInfo[0]?.companiesPic]"
                  fit="cover" />
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 屠宰信息标签页 -->
        <el-tab-pane label="屠宰信息" name="slaughter">
          <div style="padding: 0 0;">
            <el-button plain @click="Handlerupdatekill">
              修改屠宰信息
            </el-button>
            <el-button plain @click="Handleraddkillbutton">
              添加屠宰信息
            </el-button>
            <!-- 屠宰信息修改弹窗 -->
            <el-dialog v-model="Handupdatekill" title="修改屠宰信息" width="500">
              <el-form :model="killInfoUpdate">
                <el-form-item label="到场均重" :label-width="formLabelWidth">
                  <el-input v-model="killInfoUpdate.height" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="killInfoUpdate">
                <el-form-item label="到场时间" :label-width="formLabelWidth">
                  <el-date-picker v-model="killInfoUpdate.beginTime" type="datetime" placeholder="选择日期时间"
                    format="YYYY年MM月DD日 HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
              </el-form>
              <el-form :model="killInfoUpdate">
                <el-form-item label="屠宰时间" :label-width="formLabelWidth">
                  <el-date-picker v-model="killInfoUpdate.endTime" type="datetime" placeholder="选择日期时间"
                    format="YYYY年MM月DD日 HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
              </el-form>
              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="Handupdatekill = false">取消</el-button>
                  <el-button type="primary" @click="updatekill">
                    修改
                  </el-button>
                </div>
              </template>
            </el-dialog>

            <!-- 屠宰信息添加弹窗 -->
            <el-dialog v-model="Handleraddkill" title="修改屠宰信息" width="500">
              <el-form :model="killInfoAdd">
                <el-form-item label="到场均重" :label-width="formLabelWidth">
                  <el-input v-model="killInfoAdd.height" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="killInfoAdd">
                <el-form-item label="到场时间" :label-width="formLabelWidth">
                  <el-date-picker v-model="killInfoAdd.beginTime" type="datetime" placeholder="选择日期时间"
                    format="YYYY年MM月DD日 HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
              </el-form>
              <el-form :model="killInfoAdd">
                <el-form-item label="屠宰时间" :label-width="formLabelWidth">
                  <el-date-picker v-model="killInfoAdd.endTime" type="datetime" placeholder="选择日期时间"
                    format="YYYY年MM月DD日 HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
              </el-form>
              <el-form :model="killInfoAdd">
                <el-form-item label="图片" :label-width="formLabelWidth">
                  <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                    :src="killInfoAdd.killPic" :preview-src-list="[killInfoAdd.killPic]" fit="cover" />
                  <el-upload class="upload-demo" :http-request="uploadPic" :on-success="handlePicSuccess"
                    :before-upload="beforeUpload" :limit="1" :file-list="picFileList" list-type="picture" name="file">
                    <el-icon class="upload-icon">
                      <Plus />
                    </el-icon>
                    <template #tip>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-form>
              <el-form :model="killInfoAdd">
                <el-form-item label="屠宰企业" :label-width="formLabelWidth">
                  <el-select v-model="killInfoAdd.businessId" placeholder="请选择">
                    <el-option label="爱莎兔公司" value="1" />
                    <el-option label="喜欢屠宰兔公司" value="2" />
                  </el-select>
                </el-form-item>
              </el-form>
              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="Handleraddkill = false">取消</el-button>
                  <el-button type="primary" @click="addkill">
                    添加
                  </el-button>
                </div>
              </template>
            </el-dialog>

            <!-- 屠宰信息块 -->
            <div style="padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">屠宰信息</div>
              </div>
              <table>
                <tbody>
                  <tr>
                    <td>批次： {{ basicInfo.production }}</td> &emsp; &emsp;
                    <td>到场均重： {{ killInfo[0]?.height || '-' }}</td>
                  </tr>
                  <tr>
                    <td> 到场时间: {{ killInfo[0]?.beginTime ? moment(killInfo[0].beginTime).format("YYYY年MM月DD日 hh:mm:ss")
                      : '-' }}
                    </td> &emsp; &emsp;
                    <td> 屠宰时间: {{ killInfo[0]?.endTime ? moment(killInfo[0].endTime).format("YYYY年MM月DD日 hh:mm:ss") :
                      '-' }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <!-- 相关资质  -->
            <div
              style="margin-top:12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">相关资质</div>
                <el-button plain @click="addQualificationPic" :disabled="qualificationPics.length >= 9">
                  新增
                </el-button>
              </div>
              <div style="display:flex; gap:12px; flex-wrap:wrap;">
                <div v-for="(pic, index) in qualificationPics" :key="index" style="position: relative;">
                  <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;" :src="pic"
                    :preview-src-list="qualificationPics" fit="cover" />
                  <el-button type="danger" size="small" circle
                    style="position: absolute; top: -8px; right: -8px; width: 20px; height: 20px; font-size: 12px;"
                    @click="deleteQualificationPic(index)">
                    ×
                  </el-button>
                </div>
              </div>
            </div>
            <!--企业信息 -->
            <div
              style="margin-top:12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">企业信息</div>
                <el-button plain @click="HandlerupdatekillCompany">
                  修改企业信息
                </el-button>
                <!-- 屠宰企业信息修改弹窗 -->
                <el-dialog v-model="HandupdatekillCompany" title="修改屠宰企业信息" width="500">
                  <el-form :model="killCompanyUpdate">
                    <el-form-item label="公司名称" :label-width="formLabelWidth">
                      <el-input v-model="killCompanyUpdate.businessName" autocomplete="off" />
                    </el-form-item>
                  </el-form>
                  <el-form :model="killCompanyUpdate">
                    <el-form-item label="成立时间" :label-width="formLabelWidth">
                      <el-date-picker v-model="killCompanyUpdate.createDate" type="date" placeholder="选择日期"
                        format="YYYY年MM月DD日" value-format="YYYY-MM-DD" />
                    </el-form-item>
                  </el-form>
                  <el-form :model="killCompanyUpdate">
                    <el-form-item label="公司地址" :label-width="formLabelWidth">
                      <el-input v-model="killCompanyUpdate.businessAdd" autocomplete="off" />
                    </el-form-item>
                  </el-form>
                  <el-form :model="killCompanyUpdate">
                    <el-form-item label="公司简介" :label-width="formLabelWidth">
                      <el-input v-model="killCompanyUpdate.introduction" autocomplete="off" type="textarea" :rows="3" />
                    </el-form-item>
                  </el-form>
                  <template #footer>
                    <div class="dialog-footer">
                      <el-button @click="HandupdatekillCompany = false">取消</el-button>
                      <el-button type="primary" @click="updatekillCompany">
                        修改
                      </el-button>
                    </div>
                  </template>
                </el-dialog>
              </div>
              <div style="display:grid; grid-template-columns: repeat(1, minmax(260px, 1fr)); gap: 12px;">
                <table style="width: 100%;border-collapse: collapse;">
                  <tbody>
                    <tr>
                      <td>公司名称： {{ killInfo[0]?.businessName || '-' }}</td>
                      <td>成立时间： {{ killInfo[0]?.createDate ? moment(killInfo[0].createDate).format("YYYY年MM月DD日") : '-'
                      }}</td>
                    </tr>
                    <tr>
                      <td>公司地址： {{ killInfo[0]?.businessAdd || '-' }}</td>
                    </tr>
                    <tr>
                      <td>公司简介： {{ killInfo[0]?.introduction || '-' }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <!--企业图片 -->
            <div
              style="margin-top:12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">企业图片</div>
              </div>
              <div style="display:flex; gap:12px; flex-wrap:wrap;">
                <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                  :src="breedingInfo[0]?.companiesPic" :preview-src-list="[breedingInfo[0]?.companiesPic]"
                  fit="cover" />
                <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                  :src="breedingInfo[0]?.companiesPic" :preview-src-list="[breedingInfo[0]?.companiesPic]"
                  fit="cover" />
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!--深加工信息标签页 -->
        <el-tab-pane label="深加工信息" name="processing">
          <div style="padding: 0 0;">
            <el-button plain @click="Handlerupdateprocess">
              修改深加工信息
            </el-button>
            <el-button plain @click="Handleraddprocess">
              添加深加工信息
            </el-button>
            <!-- 深加工信息修改弹窗 -->
            <el-dialog v-model="Handupdateprocess" title="修改深加工信息" width="500">
              <el-form :model="processInfoUpdate">
                <el-form-item label="班组" :label-width="formLabelWidth">
                  <el-input v-model="processInfoUpdate.team" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="processInfoUpdate">
                <el-form-item label="负责人" :label-width="formLabelWidth">
                  <el-input v-model="processInfoUpdate.chargeName" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="processInfoUpdate">
                <el-form-item label="公司名称" :label-width="formLabelWidth">
                  <el-select v-model="processInfoUpdate.corporateId" placeholder="请选择">
                    <el-option label="就爱加工有限公司" value="1" />
                    <el-option label="蓝加工有限公司" value="2" />
                  </el-select>
                </el-form-item>
              </el-form>
              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="Handupdateprocess = false">取消</el-button>
                  <el-button type="primary" @click="updateprocess">
                    修改
                  </el-button>
                </div>
              </template>
            </el-dialog>

            <!-- 深加工信息添加弹窗 -->
            <el-dialog v-model="Handaddprocess" title="添加深加工信息" width="500">
              <el-form :model="processInfoadd">
                <el-form-item label="班组" :label-width="formLabelWidth">
                  <el-input v-model="processInfoadd.team" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="processInfoadd">
                <el-form-item label="负责人" :label-width="formLabelWidth">
                  <el-input v-model="processInfoadd.chargeName" autocomplete="off" />
                </el-form-item>
              </el-form>
              <el-form :model="processInfoadd">
                <el-form-item label="公司名称" :label-width="formLabelWidth">
                  <el-select v-model="processInfoadd.corporateId" placeholder="请选择">
                    <el-option label="就爱加工有限公司" value="1" />
                    <el-option label="蓝加工有限公司" value="2" />
                  </el-select>
                </el-form-item>
              </el-form>
              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="Handaddprocess = false">取消</el-button>
                  <el-button type="primary" @click="addprocess">
                    添加
                  </el-button>
                </div>
              </template>
            </el-dialog>

            <!-- 深加工信息块 -->
            <div style="padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb; ">深加工信息</div>
              </div>
              <div style="display:grid; grid-template-columns: repeat(2, minmax(160px, 1fr)); gap: 12px;">
                <table>
                  <tbody>
                    <tr>
                      <td>班组： {{ processInfo[0]?.team || '-' }}</td>
                      <td>负责人： {{ processInfo[0]?.chargeName || '-' }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <!-- 食品安全 -->
            <div
              style="margin-top:12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">食品安全</div>
              </div>
              <div style="display:flex; gap:12px; flex-wrap:wrap;">
                <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                  :src="processInfo[0]?.pic" :preview-src-list="[processInfo[0]?.pic]" fit="cover" />&emsp;
                <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                  :src="processInfo[0]?.pic" :preview-src-list="[processInfo[0]?.pic]" fit="cover" />
              </div>
            </div>
            <!-- 供应商信息 -->
            <div
              style="margin-top:12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div>
                <div
                  style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                  <div style="font-weight:600;color: #3791eb;">供应商信息</div>
                </div>
                <!-- 原料信息 -->
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px;">
                  <div style="font-weight:700; margin:5px">原料</div>
                  <el-button plain @click="addMaterialPic" :disabled="materialPics.length >= 9">
                    新增
                  </el-button>
                </div>
                <div style="display:grid; grid-template-columns: repeat(1, minmax(160px, 1fr)); gap: 12px;">
                  <table>
                    <tr>
                      <td>生产批次:&emsp;{{ basicInfo.production }}</td>
                    </tr>
                    <tr>
                      <td>
                        <u>相关材料</u>: &emsp;
                        <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                          :src="processInfo[0]?.pic" :preview-src-list="[processInfo[0]?.pic]" fit="cover" />
                        <div style="display:flex; gap:12px; flex-wrap:wrap;">
                          <div v-for="(pic, index) in materialPics" :key="index" style="position: relative;">
                            <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                              :src="pic" :preview-src-list="materialPics" fit="cover" />
                            <el-button type="danger" size="small" circle
                              style="position: absolute; top: -8px; right: -8px; width: 20px; height: 20px; font-size: 12px;"
                              @click="deleteMaterialPic(index)">
                              ×
                            </el-button>
                          </div>
                        </div>
                      </td>
                    </tr>
                  </table>
                </div>
                <!-- 辅料信息  -->
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px;">
                  <div style="font-weight:700; margin: 5px;">辅料</div>
                  <el-button plain @click="addAuxiliaryPic" :disabled="auxiliaryPics.length >= 9">
                    新增
                  </el-button>
                </div>
                <div style="display:grid; grid-template-columns: repeat(1, minmax(160px, 1fr)); gap: 12px;">
                  <table>
                    <tr>
                      <td>生产批次:&emsp;{{ basicInfo.production }}</td>
                    </tr>
                    <tr>
                      <td>
                        <u>相关材料</u>: &emsp;
                        <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                          :src="processInfo[0]?.pic" :preview-src-list="[processInfo[0]?.pic]" fit="cover" />
                        <div style="display:flex; gap:12px; flex-wrap:wrap;">
                          <div v-for="(pic, index) in auxiliaryPics" :key="index" style="position: relative;">
                            <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                              :src="pic" :preview-src-list="auxiliaryPics" fit="cover" />
                            <el-button type="danger" size="small" circle
                              style="position: absolute; top: -8px; right: -8px; width: 20px; height: 20px; font-size: 12px;"
                              @click="deleteAuxiliaryPic(index)">
                              ×
                            </el-button>
                          </div>
                        </div>
                      </td>
                    </tr>
                  </table>
                </div>
                <!-- 添加剂信息  -->
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px;">
                  <div style="font-weight:700; margin: 5px;">添加剂</div>
                  <el-button plain @click="addAdditivePic" :disabled="additivePics.length >= 9">
                    新增
                  </el-button>
                </div>
                <div style="display:grid; grid-template-columns: repeat(1, minmax(160px, 1fr)); gap: 12px;">
                  <table>
                    <tr>
                      <td>生产批次:&emsp;{{ basicInfo.production }}</td>
                    </tr>
                    <tr>
                      <td>
                        <u>相关材料</u>: &emsp;
                        <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                          :src="processInfo[0]?.pic" :preview-src-list="[processInfo[0]?.pic]" fit="cover" />
                        <div style="display:flex; gap:12px; flex-wrap:wrap;">
                          <div v-for="(pic, index) in additivePics" :key="index" style="position: relative;">
                            <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                              :src="pic" :preview-src-list="additivePics" fit="cover" />
                            <el-button type="danger" size="small" circle
                              style="position: absolute; top: -8px; right: -8px; width: 20px; height: 20px; font-size: 12px;"
                              @click="deleteAdditivePic(index)">
                              ×
                            </el-button>
                          </div>
                        </div>
                      </td>
                    </tr>
                  </table>
                </div>
                <!-- 包材信息  -->
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px;">
                  <div style="font-weight:750; margin: 5px;">包材</div>
                  <el-button plain @click="addPackagingPic" :disabled="packagingPics.length >= 9">
                    新增
                  </el-button>
                </div>
                <div style="display:grid; grid-template-columns: repeat(1, minmax(160px, 1fr)); gap: 12px;">
                  <table>
                    <tr>
                      <td>生产批次:&emsp;{{ basicInfo.production }}</td>
                    </tr>
                    <tr>
                      <td>
                        <u>相关材料</u>: &emsp;
                        <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                          :src="processInfo[0]?.pic" :preview-src-list="[processInfo[0]?.pic]" fit="cover" />
                        <div style="display:flex; gap:12px; flex-wrap:wrap;">
                          <div v-for="(pic, index) in packagingPics" :key="index" style="position: relative;">
                            <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                              :src="pic" :preview-src-list="packagingPics" fit="cover" />
                            <el-button type="danger" size="small" circle
                              style="position: absolute; top: -8px; right: -8px; width: 20px; height: 20px; font-size: 12px;"
                              @click="deletePackagingPic(index)">
                              ×
                            </el-button>
                          </div>
                        </div>
                      </td>
                    </tr>
                  </table>
                </div>
              </div>
            </div>
            <!--企业信息 -->
            <div
              style="margin-top:12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">企业信息</div>
              </div>
              <div style="display:grid; grid-template-columns: repeat(1, minmax(220px, 1fr)); gap: 12px;">
                <table style="width: 100%;border-collapse: collapse;">
                  <tbody>
                    <tr>
                      <td>公司名称： {{ processInfo[0]?.corporateName || '-' }}</td>
                      <td>生产许可证： {{ basicInfo.expNumber }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <!--企业图片 -->
            <div
              style="margin-top:12px; padding:16px 20px; background:#fff; border-radius:8px; box-shadow:0 2px 4px rgba(0,0,0,0.06);">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 12px; border-bottom: 2px solid #e5e7eb;">
                <div style="font-weight:600;color: #3791eb;">企业图片</div>
              </div>
              <div style="display:flex; gap:12px; flex-wrap:wrap;">
                <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                  :src="breedingInfo[0]?.companiesPic" :preview-src-list="[breedingInfo[0]?.companiesPic]"
                  fit="cover" />
                <el-image style="width: 120px; height: 120px; border-radius: 6px; overflow: hidden;"
                  :src="breedingInfo[0]?.companiesPic" :preview-src-list="[breedingInfo[0]?.companiesPic]"
                  fit="cover" />
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import myAxios from '@/http/MyAxios'
import moment from 'moment'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'


const Handupdatefeed = ref(false)
const Handaddfeed = ref(false)
const Handlerupdatecompanies = ref(false)
const formLabelWidth = '140px'

const route = useRoute()

const Handlerupdatefeed = () => {
  Object.assign(breedingInfoupdate.value, breedingInfo.value[0])
  Handupdatefeed.value = true
}

const Handleraddfeed = () => {
  // 重置添加表单数据
  breedingInfoadd.value = {
    "sourceId": basicInfo.value.SourceId,
    "feedVariety": "",
    "feedSource": "",
    "feedDays": "",
    "feedFoodName": "",
    "feedName": "",
    "leaveDate": "",
    "companiesId": null,
    "pic": "",
  }
  Handaddfeed.value = true
}

//养殖企业修改
const Handlerupdate = () => {
  // 根据养殖基础信息中的companiesId查询企业信息
  if (breedingInfo.value[0]?.companiesId) {
    myAxios.get("/api/Feed/ListCompanies", { params: { CompaniesId: breedingInfo.value[0].companiesId } }).then(res => {
      if (res.data.data) {
        // 手动设置每个字段，确保数据结构正确
        const companyData = res.data.data[0];
        UpdateCompaniesdatafeed.value = {
          id: companyData.id || companyData.companiesId || breedingInfo.value[0].companiesId,
          companiesName: companyData.companiesName,
          chargeName: companyData.chargeName,
          animalNumber: companyData.animalNumber,
          pic: companyData.pic
        };
      }
      Handlerupdatecompanies.value = true
    })
  }
}

//屠宰修改
const Handlerupdatekill = () => {
  Object.assign(killInfoUpdate.value, killInfo.value[0])
  Handupdatekill.value = true
}

const Handleraddkillbutton = () => {
  Handleraddkill.value = true
}

const Handlerupdateprocess = () => {
  Object.assign(processInfoUpdate.value, processInfo.value[0])
  Handupdateprocess.value = true
}



const Handleraddprocess = () => {
  Handaddprocess.value = true
}

// 屠宰企业信息修改
const HandlerupdatekillCompany = () => {
  killCompanyUpdate.value.id = killInfo.value[0].businessId
  killCompanyUpdate.value.introduction = killInfo.value[0].introduction
  killCompanyUpdate.value.createDate = killInfo.value[0].createDate
  killCompanyUpdate.value.businessPic = killInfo.value[0].businessPic
  killCompanyUpdate.value.businessName = killInfo.value[0].businessName
  killCompanyUpdate.value.businessAdd = killInfo.value[0].businessAdd
  console.log(killCompanyUpdate.value);
  HandupdatekillCompany.value = true
}

const basicInfo = ref({
  SourceId: route.query.SourceId,
  shopName: route.query.shopName,
  production: route.query.production,
  expiration: route.query.expiration,
  expNumber: route.query.expNumber,
  enterprise: route.query.enterprise,
  shopPic: route.query.shopPic,
  pics: route.query.pic ? [route.query.pic] : []
})

// 养殖信息
const breedingInfo = ref([
  {
    "id": "",
    "sourceId": "",
    "feedVariety": "",
    "feedSource": "",
    "feedDays": "",
    "feedFoodName": "",
    "feedName": "",
    "leaveDate": "",
    "healthType": "",
    "healthWay": "",
    "companiesId": "",
    "companiesName": "",
    "pic": "",
    "chargeName": "",
    "animalNumber": "",
    "companiesPic": ""
  }])

const healthInfo = ref([{
  "id": 0,
  "sourceId": "",
  "feedDays": 0,
  "healthType": "string",
  "healthWay": "string"
}])

// 养殖信息修改
const breedingInfoupdate = ref({
  "id": "",
  "sourceId": "",
  "feedVariety": "",
  "feedSource": "",
  "feedDays": "",
  "feedFoodName": "",
  "feedName": "",
  "leaveDate": "",
  "companiesId": "",
  "pic": "",
})

// 养殖信息添加
const breedingInfoadd = ref({
  "sourceId": basicInfo.value.SourceId,
  "feedVariety": "",
  "feedSource": "",
  "feedDays": "",
  "feedFoodName": "",
  "feedName": "",
  "leaveDate": "",
  "companiesId": null,
  "pic": "",
})

const UpdateCompaniesdata = ref({
  "id": breedingInfo.value[0].companiesId,
  "companiesName": "",
  "chargeName": "",
  "animalNumber": 0,
  "pic": ""
})

const UpdateCompaniesdatafeed = ref({
  "id": "",
  "companiesName": "",
  "chargeName": "",
  "animalNumber": 0,
  "pic": ""
})

//屠宰显示信息
const killInfo = ref([
  {
    "id": "",
    "sourceId": "",
    "height": "",
    "beginTime": "",
    "endTime": "",
    "killPic": "",
    "businessId": "",
    "businessName": "",
    "createDate": "",
    "businessAdd": "",
    "introduction": "",
    "businessPic": ""
  }])

//屠宰信息添加
const killInfoAdd = ref({
  "sourceId": basicInfo.value.SourceId,
  "height": 0,
  "beginTime": "2025-08-25T00:39:33.956Z",
  "endTime": "2025-08-25T00:39:33.956Z",
  "killPic": "string",
  "businessId": null
})


// 屠宰信息修改
const killInfoUpdate = ref({
  "id": "",
  "sourceId": "",
  "height": "",
  "beginTime": "",
  "endTime": "",
  "killPic": "",
  "businessId": "",
  "businessName": "",
  "createDate": "",
  "businessAdd": "",
  "introduction": "",
  "businessPic": ""
})

// 屠宰企业信息修改
const killCompanyUpdate = ref({
  "id": killInfo.value[0].businessId,
  "businessName": "",
  "createDate": "",
  "businessAdd": "",
  "introduction": "",
  "businessPic": ""
})

const HandupdatekillCompany = ref(false)

//添加深加工信息
const processInfoadd = ref({
  "sourceId": killInfo.value[0].id,
  "team": "",
  "chargeName": "",
  "foodSafetyId": 6,
  "corporateId": null
})

// 深加工信息修改
const processInfoUpdate = ref({
  "id": "",
  "sourceId": "",
  "team": "",
  "chargeName": "",
  "foodSafetyId": "",
  "pic": "",
  "corporateId": "",
  "corporateName": "",
  "corporate": "",
  "corporatePic": ""
})

const Handupdatekill = ref(false)
const Handleraddkill = ref(false)
const Handupdateprocess = ref(false)
const Handaddprocess = ref(false)

// 深加工信息
const processInfo = ref([
  {
    "id": "",
    "sourceId": "",
    "team": "",
    "chargeName": "",
    "foodSafetyId": "",
    "pic": "",
    "corporateId": "",
    "corporateName": "",
    "corporate": "",
    "corporatePic": ""
  }])

//供应商信息
const vendorInfo = ref([{
  "id": "",
  "sourceId": "",
  "materialsId": "",
  "materialsName": "",
  "materialsPic": "",
  "excipientsId": "",
  "excipientsName": "",
  "excipientsPic": "",
  "additiveId": "",
  "additiveName": "",
  "additivePic": "",
  "stuffId": "",
  "stuffName": "",
  "stuffPic": ""
}])

//养殖企业信息
const compianData = ref([{
  "id": "",
  "companiesName": "",
  "chargeName": "",
  "animalNumber": "",
  "pic": ""
}])

const picFileList = ref([])
const breedingPicFileList = ref([])
const breedingPicAddFileList = ref([])
const productPicFileList = ref([])


//养殖
const list = () => {
  myAxios.get("/api/Feed/ListFeed", { params: { SourceId: route.query.SourceId } }).then(res => {
    breedingInfo.value = res.data.data
    // 养殖信息加载完成后，查询企业信息
    if (breedingInfo.value[0]?.companiesId) {
      UpdateCompaniesdatalist()
    }
    // 初始化动检证图片数据
    if (breedingInfo.value[0]?.pic) {
      inspectionPics.value = [breedingInfo.value[0].pic]
    } else {
      inspectionPics.value = []
    }
    // 初始化相关资质图片数据
    if (basicInfo.value.pics && basicInfo.value.pics.length > 0) {
      qualificationPics.value = basicInfo.value.pics.filter((pic: any) => typeof pic === 'string')
    } else {
      qualificationPics.value = []
    }
    // 初始化辅料、添加剂、包材图片数据（暂时为空数组，后续可根据实际数据源调整）
    auxiliaryPics.value = []
    additivePics.value = []
    packagingPics.value = []
    // 初始化原料图片数据
    materialPics.value = []
  })
}
//屠宰
const killlist = () => {
  myAxios.get("/api/Kill/ListKill", { params: { Id: route.query.SourceId } }).then(res => {
    killInfo.value = res.data.data
  })
}
//深加工
const processlist = () => {
  myAxios.get("/api/Process/ListProcess", { params: { SourceId: route.query.SourceId } }).then(res => {
    processInfo.value = res.data.data
    console.log(processInfo.value);
  })
}

//供货商
const vendorlist = () => {
  myAxios.get("/api/Vendor/ListVendor", { params: { SourceId: route.query.SourceId } }).then(res => {
    vendorInfo.value = res.data.data
    console.log(vendorInfo.value)
  })
}

//养殖企业信息
const UpdateCompaniesdatalist = () => {
  // 根据养殖基础信息中的companiesId查询企业信息
  if (breedingInfo.value[0]?.companiesId) {
    myAxios.get("/api/Feed/ListCompanies", { params: { CompaniesId: breedingInfo.value[0].companiesId } }).then(res => {
      if (res.data.data) {
        UpdateCompaniesdata.value = res.data.data[0]
      } else {
        console.warn("未找到企业信息");
      }
    })
  }
}

///修改养殖信息
const updatefeed = () => {
  myAxios.post("/api/Feed/UpdateFeed", breedingInfoupdate.value).then(res => {
    if (res.data.code == 10200) {
      ElMessage.success(res.data.message);
      list()
      Handupdatefeed.value = false
    }
  })
}

// 根据下标新增健康信息行
const addHealthInfoAtIndex = (index: any) => {
  const newRow = {
    id: health.value.length + 1,
    sourceId: basicInfo.value.SourceId,
    feedDays: "",
    healthType: "",
    healthWay: "",
    isNew: true,
    isEditing: false
  }
  health.value.splice(index, 0, newRow)
}


// 根据下标删除保健信息行
const deleteHealthInfo = (index: number) => {
  const row = health.value[index]
  if (row && row.id) {
    myAxios.post("/api/Feed/DeleteHealth", { id: row.id }).then(res => {
      if (res.data.code == 10200) {
        ElMessage.success('删除成功')
        healthdata() // 重新加载数据
      } else {
        ElMessage.error('删除失败')
      }
    }).catch(() => {
      ElMessage.error('删除失败')
    })
  } else {
    // 如果是新增的行（没有id），直接删除
    health.value.splice(index, 1)
  }
}

// 验证数字输入
const validateNumber = (value: string, field: string) => {
  if (value && !/^\d+$/.test(value)) {
    ElMessage.error('饲养天数只能输入数字');
    return false
  }
  return true
}

// 验证文本输入
const validateText = (value: string, field: string) => {
  if (value && /[，。？！、；：""''（）【】]/.test(value)) {
    ElMessage.error('不允许输入特殊字符');
    return false
  }
  return true
}

// 编辑保健信息
const editHealthInfo = (row: any) => {
  row.isEditing = true
  row.originalData = { ...row }
}

// 取消编辑
const cancelEdit = (row: any) => {
  row.isEditing = false
  Object.assign(row, row.originalData)
  delete row.originalData
}

// 取消新增
const cancelAdd = (index: number) => {
  health.value.splice(index, 1)
}

// 保存保健信息
const saveHealthInfo = (row: any) => {
  // 验证必填项
  if (!row.feedDays) {
    ElMessage.error('请填写饲养天数')
    return
  }
  if (!row.healthType) {
    ElMessage.error('请填写保健方式')
    return
  }
  if (!row.healthWay) {
    ElMessage.error('请填写保健方法')
    return
  }

  // 验证数字格式
  if (!validateNumber(row.feedDays, 'feedDays')) {
    return
  }

  // 验证文本格式
  if (!validateText(row.healthType, 'healthType') || !validateText(row.healthWay, 'healthWay')) {
    return
  }

  // 判断是新增还是修改
  if (row.isNew) {
    // 新增操作
    const saveData = {
      sourceId: basicInfo.value.SourceId,
      feedDays: row.feedDays,
      healthType: row.healthType,
      healthWay: row.healthWay
    }

    myAxios.post("/api/Feed/AddHealth", saveData).then(res => {
      if (res.data.code == 10200) {
        ElMessage.success('保存成功')
        healthdata() // 重新加载数据
      } else {
        ElMessage.error('保存失败')
      }
    }).catch(() => {
      ElMessage.error('保存失败')
    })
  } else {
    // 修改操作
    const updateData = {
      id: row.id,
      sourceId: basicInfo.value.SourceId,
      feedDays: row.feedDays,
      healthType: row.healthType,
      healthWay: row.healthWay
    }

    myAxios.post("/api/Feed/UpdateHealth", updateData).then(res => {
      if (res.data.code == 10200) {
        ElMessage.success('修改成功')
        row.isEditing = false
        delete row.originalData
        healthdata() // 重新加载数据
      } else {
        ElMessage.error('修改失败')
      }
    }).catch(() => {
      ElMessage.error('修改失败')
    })
  }
}

///添加养殖信息
const addfeed = () => {
  myAxios.post("/api/Feed/AddFeed", breedingInfoadd.value).then(res => {
    console.log(breedingInfoadd.value);
    if (res.data.code == 10200) {
      ElMessage.success(res.data.message);
      list()
      Handaddfeed.value = false
    }
  })
}

///修改养殖公司信息
const updateCompanies = () => {
  console.log(UpdateCompaniesdatafeed.value);
  myAxios.post("/api/Feed/UpdateCompanies", UpdateCompaniesdatafeed.value).then(res => {
    if (res.data.code == 10200) {
      ElMessage.success(res.data.message);
      Handlerupdatecompanies.value = false
      list()
      killlist()
      processlist()
      vendorlist()
      UpdateCompaniesdatalist() // 重新加载企业信息
    }
  })
}
///添加屠宰信息
const addkill = () => {
  myAxios.post("/api/Kill/AddKill", killInfoAdd.value).then(res => {
    if (res.data.code == 10200) {
      ElMessage.success(res.data.message);
      list()
      killlist()
      processlist()
      vendorlist()
      Handupdatekill.value = false
    }
  })
}


///修改屠宰信息
const updatekill = () => {
  myAxios.post("/api/Kill/UpdateKill", killInfoUpdate.value).then(res => {
    if (res.data.code == 10200) {
      ElMessage.success(res.data.message);
      list()
      killlist()
      processlist()
      vendorlist()
      Handupdatekill.value = false
    }
  })
}

///修改屠宰企业信息
const updatekillCompany = () => {
  myAxios.post("/api/Kill/UpdateBusiness", killCompanyUpdate.value).then(res => {
    if (res.data.code == 10200) {
      ElMessage.success(res.data.message);
      HandupdatekillCompany.value = false
      list()
      killlist()
      processlist()
      vendorlist()

    }
  })
}

//深加工添加
const addprocess = () => {
  myAxios.post("/api/Process/AddProcess", processInfoadd.value).then(res => {
    if (res.data.code == 10200) {
      ElMessage.success(res.data.message);
      Handupdateprocess.value = false
      list()
      killlist()
      processlist()
      vendorlist()
    }
  })
}

///修改深加工信息
const updateprocess = () => {
  myAxios.post("/api/Process/UpdateProcess", processInfoUpdate.value).then(res => {
    if (res.data.code == 10200) {
      ElMessage.success(res.data.message);
      Handupdateprocess.value = false
      list()
      killlist()
      processlist()
      vendorlist()
    }
  })
}

// 处理图片上传
const handleImageChange = (uploadFile: any) => {
  const file = uploadFile.raw
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      if (e.target && typeof e.target.result === 'string') {
        UpdateCompaniesdata.value.pic = e.target.result
      }
    }
    reader.readAsDataURL(file)
  }
}

// 图片上传  屠宰图片
const handlePicSuccess = (res: any) => {
  // 请求中的data
  if (res && res.data) {
    killInfoAdd.value.killPic = res.data
    ElMessage.success('封面图上传成功')
  } else {
    ElMessage.error('封面图上传失败')
  }
}

//  屠宰图片
const uploadPic = (options: any) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('file', file)

  myAxios.post('/api/Source/Upload', formData)
    .then(response => {
      onSuccess(response.data, file)
    })
    .catch(error => {
      onError(error)
    })
}

// 产品检验图片上传处理
const handleProductPicSuccess = (res: any) => {
  if (res && res.data) {
    basicInfo.value.pics.push(res.data)
    ElMessage.success('产品检验图片上传成功')
  } else {
    ElMessage.error('产品检验图片上传失败')
  }
}

// 产品检验图片上传
const uploadProductPic = (options: any) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('file', file)

  myAxios.post('/api/Source/Upload', formData)
    .then(response => {
      onSuccess(response.data, file)
    })
    .catch(error => {
      onError(error)
    })
}

//图片上传限制信息
const beforeUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt500K = file.size / 1024 < 500

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt500K) {
    ElMessage.error('上传图片大小不能超过 500KB!')
    return false
  }
  return true
}

// 养殖信息动检证图片上传
const uploadBreedingPic = (options: any) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('file', file)

  myAxios.post('/api/Source/Upload', formData)
    .then(response => {
      onSuccess(response.data, file)
    })
    .catch(error => {
      onError(error)
    })
}

// 养殖信息动检证图片上传成功回调
const handleBreedingPicSuccess = (res: any) => {
  if (res && res.data) {
    breedingInfoupdate.value.pic = res.data
    ElMessage.success('动检证图片上传成功')
  } else {
    ElMessage.error('动检证图片上传失败')
  }
}

// 养殖信息企业图片上传
const uploadBreedingCompanyPic = (options: any) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('file', file)

  myAxios.post('/api/Source/Upload', formData)
    .then(response => {
      onSuccess(response.data, file)
    })
    .catch(error => {
      onError(error)
    })
}

// 养殖信息添加动检证图片上传
const uploadBreedingPicAdd = (options: any) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('file', file)

  myAxios.post('/api/Source/Upload', formData)
    .then(response => {
      onSuccess(response.data, file)
    })
    .catch(error => {
      onError(error)
    })
}

// 养殖信息添加动检证图片上传成功回调
const handleBreedingPicAddSuccess = (res: any) => {
  if (res && res.data) {
    breedingInfoadd.value.pic = res.data
    ElMessage.success('动检证图片上传成功')
  } else {
    ElMessage.error('动检证图片上传失败')
  }
}

// 养殖信息添加企业图片上传
const uploadBreedingCompanyPicAdd = (options: any) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('file', file)

  myAxios.post('/api/Source/Upload', formData)
    .then(response => {
      onSuccess(response.data, file)
    })
    .catch(error => {
      onError(error)
    })
}

//养殖企业全部
const listcompain = () => {
  myAxios.get("/api/Feed/GetAllCompanies").then(res => {
    compianData.value = res.data.data
  })
}

const health = ref<any[]>([])

// 动检证图片数组
const inspectionPics = ref<string[]>([])

// 相关资质图片数组
const qualificationPics = ref<string[]>([])

// 辅料图片数组
const auxiliaryPics = ref<string[]>([])

// 添加剂图片数组
const additivePics = ref<string[]>([])

// 包材图片数组
const packagingPics = ref<string[]>([])

// 原料图片数组
const materialPics = ref<string[]>([])

// 添加动检证图片
const addInspectionPic = () => {
  // 创建隐藏的文件输入框
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.multiple = false

  input.onchange = (event: any) => {
    const file = event.target.files[0]
    if (file) {
      // 验证文件类型和大小
      if (!beforeUpload(file)) {
        return
      }

      // 上传图片
      const formData = new FormData()
      formData.append('file', file)

      myAxios.post('/api/Source/Upload', formData)
        .then(response => {
          if (response.data && response.data.data) {
            inspectionPics.value.push(response.data.data)
            ElMessage.success('图片上传成功')
          } else {
            ElMessage.error('图片上传失败')
          }
        })
        .catch(error => {
          ElMessage.error('图片上传失败')
        })
    }
  }

  input.click()
}

// 删除动检证图片
const deleteInspectionPic = (index: number) => {
  inspectionPics.value.splice(index, 1)
  ElMessage.success('图片删除成功')
}

// 添加相关资质图片
const addQualificationPic = () => {
  // 创建隐藏的文件输入框
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.multiple = false

  input.onchange = (event: any) => {
    const file = event.target.files[0]
    if (file) {
      // 验证文件类型和大小
      if (!beforeUpload(file)) {
        return
      }

      // 上传图片
      const formData = new FormData()
      formData.append('file', file)

      myAxios.post('/api/Source/Upload', formData)
        .then(response => {
          if (response.data && response.data.data) {
            qualificationPics.value.push(response.data.data)
            ElMessage.success('图片上传成功')
          } else {
            ElMessage.error('图片上传失败')
          }
        })
        .catch(error => {
          ElMessage.error('图片上传失败')
        })
    }
  }

  input.click()
}

// 删除相关资质图片
const deleteQualificationPic = (index: number) => {
  qualificationPics.value.splice(index, 1)
  ElMessage.success('图片删除成功')
}

// 添加辅料图片
const addAuxiliaryPic = () => {
  // 创建隐藏的文件输入框
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.multiple = false

  input.onchange = (event: any) => {
    const file = event.target.files[0]
    if (file) {
      // 验证文件类型和大小
      if (!beforeUpload(file)) {
        return
      }

      // 上传图片
      const formData = new FormData()
      formData.append('file', file)

      myAxios.post('/api/Source/Upload', formData)
        .then(response => {
          if (response.data && response.data.data) {
            auxiliaryPics.value.push(response.data.data)
            ElMessage.success('图片上传成功')
          } else {
            ElMessage.error('图片上传失败')
          }
        })
        .catch(error => {
          ElMessage.error('图片上传失败')
        })
    }
  }

  input.click()
}

// 删除辅料图片
const deleteAuxiliaryPic = (index: number) => {
  auxiliaryPics.value.splice(index, 1)
  ElMessage.success('图片删除成功')
}

// 添加添加剂图片
const addAdditivePic = () => {
  // 创建隐藏的文件输入框
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.multiple = false

  input.onchange = (event: any) => {
    const file = event.target.files[0]
    if (file) {
      // 验证文件类型和大小
      if (!beforeUpload(file)) {
        return
      }

      // 上传图片
      const formData = new FormData()
      formData.append('file', file)

      myAxios.post('/api/Source/Upload', formData)
        .then(response => {
          if (response.data && response.data.data) {
            additivePics.value.push(response.data.data)
            ElMessage.success('图片上传成功')
          } else {
            ElMessage.error('图片上传失败')
          }
        })
        .catch(error => {
          ElMessage.error('图片上传失败')
        })
    }
  }

  input.click()
}

// 删除添加剂图片
const deleteAdditivePic = (index: number) => {
  additivePics.value.splice(index, 1)
  ElMessage.success('图片删除成功')
}

// 添加包材图片
const addPackagingPic = () => {
  // 创建隐藏的文件输入框
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.multiple = false

  input.onchange = (event: any) => {
    const file = event.target.files[0]
    if (file) {
      // 验证文件类型和大小
      if (!beforeUpload(file)) {
        return
      }

      // 上传图片
      const formData = new FormData()
      formData.append('file', file)

      myAxios.post('/api/Source/Upload', formData)
        .then(response => {
          if (response.data && response.data.data) {
            packagingPics.value.push(response.data.data)
            ElMessage.success('图片上传成功')
          } else {
            ElMessage.error('图片上传失败')
          }
        })
        .catch(error => {
          ElMessage.error('图片上传失败')
        })
    }
  }

  input.click()
}

// 删除包材图片
const deletePackagingPic = (index: number) => {
  packagingPics.value.splice(index, 1)
  ElMessage.success('图片删除成功')
}

// 添加原料图片
const addMaterialPic = () => {
  // 创建隐藏的文件输入框
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.multiple = false

  input.onchange = (event: any) => {
    const file = event.target.files[0]
    if (file) {
      // 验证文件类型和大小
      if (!beforeUpload(file)) {
        return
      }

      // 上传图片
      const formData = new FormData()
      formData.append('file', file)

      myAxios.post('/api/Source/Upload', formData)
        .then(response => {
          if (response.data && response.data.data) {
            materialPics.value.push(response.data.data)
            ElMessage.success('图片上传成功')
          } else {
            ElMessage.error('图片上传失败')
          }
        })
        .catch(error => {
          ElMessage.error('图片上传失败')
        })
    }
  }

  input.click()
}

// 删除原料图片
const deleteMaterialPic = (index: number) => {
  materialPics.value.splice(index, 1)
  ElMessage.success('图片删除成功')
}

const healthdata = () => {
  myAxios.get("/api/Feed/ListHealth", { params: { SourceId: basicInfo.value.SourceId } }).then(res => {
    health.value = res.data.data.map((item: any) => ({
      ...item,
      isEditing: false,
      isNew: false
    }))
    console.log(health.value);
  })
}

onMounted(() => {
  console.log("页面开始加载，SourceId:", route.query.SourceId);
  list()
  killlist()
  processlist()
  vendorlist()
  listcompain()
  healthdata()
})

</script>

<style scoped>
:deep(.el-tabs__item) {
  font-weight: 500;
}
</style>